package com.alks.function.controller.system;

import com.alibaba.fastjson.JSON;
import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.WebLogger;
import com.alks.common.data.thread.UserIdThread;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.EmptyDataException;
import com.alks.function.data.request.sys.FileExportRecordRequest;
import com.alks.function.data.vo.stock.PageDataVO;
import com.alks.function.data.vo.sys.FileExportRecordVO;
import com.alks.function.data.vo.sys.FileGenerateInfoVO;
import com.alks.function.service.system.ISysFileExportRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.List;

/**
 * @author: chen
 * @date: 2024/12/27
 * @description: 文件导出记录
 */
@Slf4j
@RestController
@AllArgsConstructor
@ApiRestController("/sys/file/export/record")
@Api(value = "文件导出记录", tags = "文件导出记录")
public class SysFileExportRecordController {

    final private ISysFileExportRecordService sysFileExportRecordService;

    @WebLogger
    @PostMapping("/page")
    @ApiOperation(value = "分页查询", tags = "文件导出记录")
    public ResponseInfo<PageDataVO<FileExportRecordVO>> termPage(@RequestBody FileExportRecordRequest request) {
        return ResponseInfo.ok(sysFileExportRecordService.termPage(request));
    }

    @WebLogger
    @PostMapping("/remove/{id}")
    @ApiOperation(value = "删除记录", tags = "文件导出记录")
    public ResponseInfo<Boolean> removeRecord(@PathVariable Long id) {
        return ResponseInfo.ok(sysFileExportRecordService.removeRecord(id));
    }

    @WebLogger
    @GetMapping(value = "/rt", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ApiOperation(value = "实时推送文件状态",tags = "文件导出记录")
    public Flux<FileGenerateInfoVO> queryRT() {
        String userId = UserIdThread.get().getUserId();
        return Flux.interval(Duration.ofSeconds(3))
            .flatMap(sequence -> {
                FileGenerateInfoVO infoVO = sysFileExportRecordService.checkStatus(userId);
                if (infoVO.getClose()) {
                    return Flux.error(new EmptyDataException(JSON.toJSONString(infoVO)));
                }
                return Mono.fromCallable(() -> infoVO);
            })
            .onErrorResume(e -> {
                // 捕获异常，记录日志或返回自定义响应
                log.info("连接已关闭: " + e.getMessage());
                if (e instanceof EmptyDataException) {
                    FileGenerateInfoVO infoVO = JSON.parseObject(e.getMessage(), FileGenerateInfoVO.class);
                    infoVO.setClose(true);
                    return Mono.fromCallable(() -> infoVO);
                } else {
                    e.printStackTrace();
                    return Mono.fromCallable(FileGenerateInfoVO::onClose);
                }
            });
    }

    @WebLogger
    @GetMapping("/download/{bucket}/{fileName}")
    @ApiOperation(value = "下载", tags = "文件导出记录")
    public void download(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
        sysFileExportRecordService.download(bucket, fileName, response);
    }

}
